package com.qhad.ads.activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.test.PerformanceTestCase;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.songheng.eastnews.apk.R;
import com.umeng.analytics.MobclickAgent;
import com.juwang.girl.util.QihuAdvertis;
import com.qhad.ads.sdk.adcore.Qhad;
import com.qhad.ads.sdk.interfaces.IQhAdEventListener;
import com.qhad.ads.sdk.interfaces.IQhBannerAd;


public class SampleBannerActivity extends Activity implements View.OnClickListener {

    private RelativeLayout adContainer = null;
    private IQhBannerAd bannerad = null;
    

    private Button banner_open_btn = null;
    private Button banner_close_btn = null;
    private Boolean hasScheled = false;
    private int failCount = 0;
    private int interval = 60 * 1000;//2分钟 

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_banner_layout);
        setTitle("条幅");
        /*
        banner_open_btn = (Button) findViewById(R.id.banner_open_btn);
        banner_open_btn.setOnClickListener(this);
        banner_close_btn = (Button) findViewById(R.id.banner_close_btn);
        banner_close_btn.setOnClickListener(this);
        */
        adContainer = (RelativeLayout) findViewById(R.id.banner_adcontainer); // 广告容器 adContainer
        adContainer.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "CLICKED1!", Toast.LENGTH_SHORT).show();
				return false;
			}
		});
        
        /**
         * 显示广告
         */
        addAds();
//        QihuAdvertis.loadQihuAdBanner(SampleBannerActivity.this, adContainer);
    }

    private void addAds() {
//        final String adSpaceid = "uauGaUop3a"; // 广告位ID adSpaceid
    	final String adSpaceid = QihuAdvertis.bannerid;
        bannerad = Qhad.showBanner(adContainer, SampleBannerActivity.this, adSpaceid, false); // 请求广告
       
        /**
         * 设置广告回调
         */
        bannerad.setAdEventListener(new IQhAdEventListener() {
            @Override
            public void onAdviewGotAdSucceed() {
            	Log.i("Banner:","onAdviewGotAdSucceed");

            }

            @Override
            public void onAdviewGotAdFail() {
            	Log.i("Banner:","onAdviewGotAdFail");
            	failCount++;
            	if(failCount<30){
            		addAds();
            	}else{
            		setResult(1);
            		finish();
            	}
            }

            @Override
            public void onAdviewRendered() {
            	Log.i("Banner:","onAdviewRendered");
            	
            	if(!hasScheled){
            		timer.schedule(task,interval, interval);
            		hasScheled = true;
            	}
            }

            @Override
            public void onAdviewIntoLandpage() {
            	Log.i("Banner:","onAdviewIntoLandpage");
            }

            @Override
            public void onAdviewDismissedLandpage() {
            	Log.i("Banner:","onAdviewDismissedLandpage");
            }

            @Override
            public void onAdviewClicked() {
            	Log.i("Banner:","onAdviewClicked");
            }

            @Override
            public void onAdviewClosed() {
            	Log.i("Banner:","onAdviewGotAdSucceed");
            }

            @Override
            public void onAdviewDestroyed() {
            	Log.i("Banner:","onAdviewGotAdSucceed");
            }
        });
    }
    Timer timer = new Timer();  
    Handler handler = new Handler(){  
   
        public void handleMessage(Message msg) {  
            switch (msg.what) { 
            case 1:
            	setSimulateClick(adContainer, 300,20);
            	
            	break;
            case 2:      
//            	ViewGroup view = (ViewGroup)adContainer.getChildAt(0);
            	sendToBack();
            	timer.cancel();
                break;      
            }      
            super.handleMessage(msg);  
        }  
           
    };
    int countTask=1;
    TimerTask task = new TimerTask(){  
   
        public void run() {  
            Message message = new Message();      
            message.what = countTask++;      
            handler.sendMessage(message);
            
        }  
           
    }; 
    
    private void setSimulateClick(View view, float x, float y) {
        long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_DOWN, x, y, 0);
        downTime += 100;
        final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_UP, x+10, y+10, 0);
        view.onTouchEvent(downEvent);
        view.onTouchEvent(upEvent);
        view.dispatchTouchEvent(downEvent);
        view.dispatchTouchEvent(upEvent);
        downEvent.recycle();
        upEvent.recycle();
        timer1.schedule(task1, interval, interval);
      }
    
    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.banner_open_btn:
//                addAds();
//                break;
//
//            case R.id.banner_close_btn:
//                bannerad.closeAds();
//                break;
//
//            default:
//                break;
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /**
         * Acvitivy销毁时调用，回收广告资源
         */
        Qhad.activityDestroy(this);
        timer.cancel();
        timer1.cancel();
    }
    
    @SuppressLint("NewApi")
	private void bringToFront(){
    	Intent intent = new Intent(getApplicationContext(), SampleBannerActivity.this.getClass());
    	/*
    	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    	intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    	intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	*/
//    	intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//    	startActivity(intent);
    	
    	if(isApplicationBroughtToBackground(getApplicationContext())){
    		ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasks = am.getRunningTasks(2);
            am.moveTaskToFront(tasks.get(1).id,ActivityManager.MOVE_TASK_WITH_HOME);
    	}else{
    		Log.i("ddd","111");
    	}
    }
    
    public  boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            String packageName = topActivity.getPackageName();
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
    
    private void sendToBack(){
    	
         //moveTaskToBack(true);
    	/*
    	dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK));
    	dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_BACK));
    	*/
    }
    Timer timer1 = new Timer();  
    int countTask1 = 1;
    Handler handler1 = new Handler(){  
   
        public void handleMessage(Message msg) {  
            switch (msg.what) {
            case 1:
            	//motionMove();
            	
            	break;
            case 2:      
            	bringToFront();
                break;
            case 3:
            	setResult(1);
            	finish();
            	timer1.cancel();
            	break;
            }      
            super.handleMessage(msg);  
        }  
           
    };
    
    TimerTask task1 = new TimerTask(){  
   
        public void run() {  
            Message message = new Message();      
            message.what = countTask1++;      
            handler1.sendMessage(message);
        }  
           
    }; 
    private void motionMove(){
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
		    	inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 240, 400, 0));
		    	inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE, 242, 402, 0));
		        
		    	inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 244, 404, 0));
		    	
			}
		}).start();
    	
    }
    
    public void onResume() {
    	super.onResume();
    	MobclickAgent.onResume(this);
    }
    
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
